frappe.ui.form.on("Journal Entry", {
    refresh: function (frm) {
        // console.log(`Journal Entry refresh frm 👉`, frm)
    },
    before_save: async function (frm) {
        if (!frm.doc.is_system_generated) {
            let 有辅助核算分录组1 = frm.doc.accounts.map(async el => {
                const 科目 = el.account
                console.log(`科目 👉`, 科目)
                const 科目doc = await frappe.db.get_doc("Account", 科目)
                console.log(`科目doc 👉`, 科目doc)
                const 辅助核算 = 科目doc.custom_辅助核算
                console.log(`el 👉`, el)
                if (辅助核算 && !el[辅助核算]) {
                    return el
                }
            })
            // let 有辅助核算分录组 = await Promise.all(有辅助核算分录组1);
            const 有辅助核算分录组 = (await Promise.all(有辅助核算分录组1)).filter(el => el !== undefined)
            console.log(`有辅助核算分录组 👉`, 有辅助核算分录组)
            if (有辅助核算分录组?.length > 0) {
                const rows = 有辅助核算分录组.map(x => "#" + x.idx)
                const accountNames = 有辅助核算分录组.map(x => x.account)
                frappe.throw(
                    __("以下分录行必须填写 辅助核算: <br> 行号: {0} <br> 科目: {1}", [
                        frappe.utils.comma_and(rows),
                        frappe.utils.comma_and(accountNames),
                    ])
                )
            }

            const title = frm.doc.title
            const 第一子项 = frm.doc.accounts[0]
            if (!title) {
                frm.doc.title = 第一子项.user_remark
            }
        }
    },
})

frappe.ui.form.on("Journal Entry Account", {
    account: async function (frm, cdt, cdn) {
        console.log(`account 字段值变化 ing👇`)
        let row = locals[cdt][cdn]
        if (!row.account) return

        const 提示余额 = await frappe.db.get_single_value("shezhi", "rijizhangpingzheng_tishiyuer")
        console.log(`提示余额 👉`, 提示余额)
        if (!提示余额) return

        //获取当前日期
        let posting_date = frm.doc.posting_date || frappe.datetime.get_today()

        frappe.call({
            method: "erpnext.accounts.utils.get_balance_on",
            args: {
                account: row.account,
                date: posting_date,
                company: frm.doc.company,
            },
            callback: function (r) {
                if (r.message !== undefined) {
                    // 输出获取的科目余额
                    let balance = r.message
                    const { 借贷, color } = amtf.util.成借贷(balance)
                    frm.set_intro(null)
                    let balance_text = `公司:${frm.doc.company};会计科目:${
                        row.account
                    };科目余额: ${借贷}记 ${format_currency(balance)}`
                    // let color = balance >= 0 ? "green" : "red"
                    // const 借贷 = balance >= 0 ? "借" : "贷"

                    frm.set_intro(__(balance_text), color)
                }
            },
        })
    },
    accounts_add(frm, cdt, cdn) {
        // console.log(`accounts_add ing👇`)
        // frappe.msgprint('A row has been added to the links table 🎉 ');
        let row = locals[cdt][cdn]
        const grid = frm.grids[0].grid
        rowEls = grid.grid_rows[row.idx - 1].row.find('[data-fieldname="account"]')
        // console.log(`rowEls 👉`, rowEls)
        // 等其他逻辑执行完，再来click
        setTimeout(() => {
            rowEls[0].click()
        }, 100)
        // rowEls[0].click()
    },
})

const accounts_add = erpnext.accounts.JournalEntry.prototype.accounts_add
erpnext.accounts.JournalEntry.prototype.accounts_add = function (doc, cdt, cdn) {
    if (typeof accounts_add === "function") {
        accounts_add.call(this, doc, cdt, cdn)
    }
    // 获取当前添加的行
    const row = frappe.get_doc(cdt, cdn)
    // console.log(`row 👉`, row)
    // 获取上一行
    const accounts = doc.accounts || []
    if (accounts.length > 1) {
        const lastRow = accounts[accounts.length - 2]
        // console.log(`lastRow 👉`, lastRow)
        // 复制上一行的摘要信息
        if (lastRow.user_remark) {
            frappe.model.set_value(cdt, cdn, "remarks", lastRow.user_remark)
            row.user_remark = lastRow.user_remark
        }
    }
}
